package control;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;


public class ControlClient {
	JMXConnector connector;
	MBeanServerConnection mbsc;
	public void setRate(int rate) throws MalformedObjectNameException, NullPointerException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException, IOException, InvalidAttributeValueException{
		 ObjectName name=new ObjectName("hwc:type=SimpleClient");
		    int serverRate=(Integer)mbsc.getAttribute(name, "Rate");
		    Attribute attribute=new Attribute("Rate", rate);
		    mbsc.setAttribute(name, attribute);
//		   double[] rates= (double[]) mbsc.getAttribute(name, "DynamicRate");
//		    for(double d:rates){
//		    	System.out.print(d+"\t");
//		    }
		    System.out.println();
	}
	public String getRates() throws MalformedObjectNameException, NullPointerException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException, IOException{
		 ObjectName name=new ObjectName("hwc:type=SimpleClient");
		    int serverRate=(Integer)mbsc.getAttribute(name, "Rate");
		   double[] rates= (double[]) mbsc.getAttribute(name, "DynamicRate");
		   StringBuffer buffer=new StringBuffer();
		   buffer.append(new Date()+":\t");
		   buffer.append("[rate:"+serverRate+"]\t");
		   double total=0;
		    for(double d:rates){
		    	total+=d;
		    	buffer.append(d+"\t");
		    }
		    buffer.append(total+"\n");
			return buffer.toString();
	}
	/**
	 * @param args
	 * @throws InterruptedException 
	 * @throws IOException 
	 * @throws ReflectionException 
	 * @throws MBeanException 
	 * @throws NullPointerException 
	 * @throws InstanceNotFoundException 
	 * @throws AttributeNotFoundException 
	 * @throws MalformedObjectNameException 
	 * @throws InvalidAttributeValueException 
	 */
	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws InterruptedException, MalformedObjectNameException, AttributeNotFoundException, InstanceNotFoundException, NullPointerException, MBeanException, ReflectionException, IOException, InvalidAttributeValueException {
		// provide a valid username and password (e.g., via program arguments)
	    String user = "root";
	    String pwd = "root";
	    String[] ips=new String[]{"192.168.3.29","192.168.3.13","192.168.3.15"};
	    //"service:jmx:rmi:///jndi/rmi://192.168.3.36:9999/jmxrmi"
	    // place the username and password in a string array of credentials that
	    // can be used when making the connection to the remote JMX agent
	    //11 点10分-->50。12:10分-->40 。 
	    //20 30  
	    int[] rates={100,};
	    Date[] dates={
	    		new Date(113, 10, 11, 12, 15, 0),
//	    		new Date(113, 10, 17, 16, 21, 0),
//	    		new Date(113, 10, 17, 16, 41, 0),
//	    		new Date(113, 10, 17, 17, 01, 0),
//	    		new Date(113, 10, 17, 17, 21, 0),
//	    		new Date(113, 10, 17, 17, 41, 0),
//	    		new Date(113, 10, 17, 18, 01, 0),
//	    		new Date(113, 10, 17, 18, 21, 0),
//	    		new Date(113, 10, 17, 18, 41, 0),
//	    		new Date(113, 10, 17, 19, 01, 0)
	    };
	    assert dates.length==rates.length;
	    File file=new File("logs");
	    if(!file.exists()){
	    	file.mkdirs();
	    }
	    final ControlClient[] clients=new ControlClient[ips.length];//修改速度
	    final ControlClient[] secondClients=new ControlClient[ips.length];//打印实时速度
	    final TimerTask[][] tasks=new TimerTask[clients.length][rates.length];//每组的前3个用来控制速度（绑定clients），第四个用来打印速度（绑定secondClient）
	    final TimerTask[] printTasks=new TimerTask[clients.length];//用来打印速度（绑定secondClient）
	    final Timer timer=new Timer();
	    for(int i=0;i<clients.length;i++){
	    	clients[i]=new ControlClient();
	    	clients[i].connect(user, pwd, "service:jmx:rmi:///jndi/rmi://"+ips[i]+":12345/jmxrmi");
	    	tasks[i]=new TimerTask[rates.length];
	    	for(int j=0;j<tasks[i].length;j++){
	    		tasks[i][j]=new MyTimerTask(clients[i],rates[j]);
	    		//设定触发时间
		    	timer.schedule(tasks[i][j], dates[j]);
		    	System.out.println(ips[i]+" will set rate "+rates[j]+" at "+ dates[j]);
	    	}
	    	secondClients[i]=new ControlClient();
	    	secondClients[i].connect(user, pwd, "service:jmx:rmi:///jndi/rmi://"+ips[i]+":12345/jmxrmi");
	    	printTasks[i]=new MyMonitorTask(secondClients[i],ips[i]);

	    	timer.scheduleAtFixedRate(printTasks[i], 5000, 5000);//d定时打印实时速度
	    }
	    
	    timer.schedule(new TimerTask() {
			@Override
			public void run() {
				for(int i=0;i<clients.length;i++){
					try {
						clients[i].connector.close();
						secondClients[i].connector.close();
						((MyMonitorTask)printTasks[i]).close();
					} catch (IOException e) {
						e.printStackTrace();
					}finally{
						timer.cancel();
					}
				}
			}
		}, new Date(113, 10, 18, 15, 15, 0));
//	    
	}
	public JMXConnector connect(String user,String pwd,String url) throws IOException, MalformedObjectNameException, NullPointerException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException{
		   String[] credentials = new String[] { user, pwd };
		    // the string array of credentials is placed in a map keyed against the
		    // well-defined credentials identifier string
		    Map<String, String[]> props = new HashMap<String, String[]>();
		    props.put("jmx.remote.credentials", credentials);
		    // supply the map of credentials to the connect call
		    JMXServiceURL address =  new JMXServiceURL(url);
		     connector = JMXConnectorFactory.connect(address, props);
		    // it is a trivial matter to get a reference for the MBean server
		    // connection to the remote agent
		    mbsc = connector.getMBeanServerConnection();
		    connector.connect();
		    /****************Client Has The Server handle******************************************/
//		    System.out.println("\nMBean count = " + mbsc.getMBeanCount());
//		    for (ObjectInstance object : mbsc.queryMBeans(null, null)) {
//	            System.out.println("object.getObjectName="+object.getObjectName());
//	        }
		    return connector;
		    
		   

		    
		   
	}
	

}
